/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package db.server.DAO;

import db.server.DTO.QueryDTO;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 *
 * @author QuangKhai
 */
public class QueryDAO {
    private Document document = null;
    
    /** Creates new QueryDAO */
    public QueryDAO(){
        DocumentBuilder builder = null;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        
        try {
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(QueryDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        document = builder.newDocument();
    }
    
    ///Generate to xml file
    public void writeQuery(QueryDTO queryDTO, String path) throws ParserConfigurationException{
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document dcmt = builder.newDocument();
        
        Element root = (Element) dcmt.createElement("QueryDTO");
        root.setAttribute("database", queryDTO.getDatabaseName());
        dcmt.appendChild(root);
        
        for(int i = 0; i < queryDTO.getQuerySentences().size(); i++){
            Element query = (Element) dcmt.createElement("query");
            query.setAttribute("contain", queryDTO.getQuerySentences().get(i));
            
            root.appendChild(query);
        }
        
        // Normalizing the DOM
        dcmt.getDocumentElement().normalize();
        
        DOMUtil.writeXmlToFile(path, dcmt);        
    }
    
    ///Read query file into QueryDTO
    public QueryDTO readQueryFile(String path){
        QueryDTO query = new QueryDTO();
        
        document = DOMUtil.parse(path);
        
        Element root = document.getDocumentElement();
        query.setDatabaseName(root.getAttribute("database"));
        
        NodeList childNode = root.getChildNodes();
        
        int num = childNode.getLength();
        
        List<String> lstRow = new ArrayList<String>();
        
        for(int i = 0; i < num; i++){
            Element node = (Element) childNode.item(i);
            
            lstRow.add(node.getAttribute("contain"));
        }                
        
        query.setQuerySentences(lstRow);
        
        return query;
    }
}
